package com.derive.education_service.web.wechat.controller;

import com.derive.education_service.common.global.ResponseMessage;
import com.derive.education_service.entity.User;
import com.derive.education_service.web.wechat.service.WxApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("wxapi")
public class WxApiController {
    @Autowired
    private WxApiService wxApiService;

    /**
     * 获取微信openId
     * @param code
     * @return
     */
    @GetMapping("getWxOpenId")
    public ResponseMessage getWxOpenId(String code) {
        Map<String, String> data = wxApiService.getWxOpenId(code);
        if (data.containsKey("error"))
            return ResponseMessage.createByErrorMessage(data.get("error"));
        else
            return ResponseMessage.createBySuccess(data);
    }

    /**
     * 获取accessToken
     * @return
     */
    @GetMapping("getAccessToken")
    public ResponseMessage getAccessToken() {
        Map<String, String> data = wxApiService.getAccessToken();
        if (data.containsKey("error"))
            return ResponseMessage.createByErrorMessage(data.get("error"));
        else
            return ResponseMessage.createBySuccess(data);
    }

    /**
     * 检查微信小程序用户是否已经存在
     * code：2 -> 用户已失效
     * @param openId
     * @return
     */
    @PostMapping("checkUser")
    public ResponseMessage checkUser(String openId) {
        User user = wxApiService.checkUser(openId);
        if (user == null) {
            return ResponseMessage.createByErrorMessage("用户未注册");
        } else {
            return user.getIsState() ? ResponseMessage.createBySuccess("用户信息",user) : ResponseMessage.createByErrorCodeMessage(2,"用户已失效");
        }
    }
}
